import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/pages/test_detail/widgets/test_card_base.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:math' as math;

class TestRadarChartBlock extends StatelessWidget {
  final ModelTestDetail? testDetail;

  const TestRadarChartBlock({Key? key, this.testDetail}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return TestCardBase(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text(
            'Multi-dimensional analysis',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              color: AppColor.color0C0A09,
              letterSpacing: 0.14,
              height: 1.26,
            ),
          ),

          SizedBox(height: 4.w),

          // 描述
          Text(
            'Comprehensively evaluate your performance and development potential in each dimension',
            style: TextStyle(
              fontSize: 12.sp,
              color: AppColor.color7F909E,
              height: 1.26,
              letterSpacing: 0.12,
            ),
          ),

          SizedBox(height: 24.w),

          // 雷达图部分
          SizedBox(
            height: 258.w,
            width: double.infinity,
            child: Stack(
              clipBehavior: Clip.none,
              alignment: Alignment.center,
              children: [
                // 多边形背景网格
                _buildRadarBackgroundGrid(),

                // 维度标签
                _buildDimensionLabels(),

                // 雷达数据图
                _buildRadarDataPolygon(),

                // 数据点
                _buildDataPoints(),
              ],
            ),
          ),

          SizedBox(height: 20.w),

          // 分数列表
          _buildScoresList(),
        ],
      ),
    );
  }

  // 构建雷达图背景网格
  Widget _buildRadarBackgroundGrid() {
    return Stack(
      alignment: Alignment.center,
      children: [
        // 最外层网格
        CustomPaint(
          size: Size(220.w, 220.w),
          painter: RadarGridPainter(
            sides: 8,
            color: AppColor.colorE4EBF0,
            strokeWidth: 1.0,
          ),
        ),

        // 第二层网格
        CustomPaint(
          size: Size(176.w, 176.w),
          painter: RadarGridPainter(
            sides: 8,
            color: AppColor.colorE4EBF0,
            strokeWidth: 1.0,
          ),
        ),

        // 第三层网格
        CustomPaint(
          size: Size(132.w, 132.w),
          painter: RadarGridPainter(
            sides: 8,
            color: AppColor.colorE4EBF0,
            strokeWidth: 1.0,
          ),
        ),

        // 第四层网格
        CustomPaint(
          size: Size(88.w, 88.w),
          painter: RadarGridPainter(
            sides: 8,
            color: AppColor.colorE4EBF0,
            strokeWidth: 1.0,
          ),
        ),

        // 最内层网格
        CustomPaint(
          size: Size(44.w, 44.w),
          painter: RadarGridPainter(
            sides: 8,
            color: AppColor.colorE4EBF0,
            strokeWidth: 1.0,
          ),
        ),

        // 轴线
        CustomPaint(
          size: Size(220.w, 220.w),
          painter: RadarAxisPainter(
            sides: 8,
            color: AppColor.colorE4EBF0,
            strokeWidth: 1.0,
          ),
        ),
      ],
    );
  }

  // 构建雷达图数据多边形
  Widget _buildRadarDataPolygon() {
    // 使用与分数列表一致的数据（按标签顺序排列）
    final List<double> dataValues = [
      0.85, // LT - Logical Thinking
      0.96, // IT/CR - Innovative Thinking / Creativity
      0.82, // CE - Communication and Expression
      0.79, // TC - Teamwork and Collaboration
      0.88, // LA - Learning and Adaptability
      0.94, // EM - Emotional Management
      0.80, // DMJ - Decision-Making and Judgment
      0.92, // EA - Execution Ability
    ];

    return CustomPaint(
      size: Size(220.w, 220.w),
      painter: RadarDataPainter(
        dataPoints: dataValues,
        sides: 8,
        fillColor: AppColor.primary.withOpacity(0.12),
        strokeColor: AppColor.primary,
        strokeWidth: 1.5,
      ),
    );
  }

  // 构建维度标签
  Widget _buildDimensionLabels() {
    final radius = 115.w; // 调整标签到中心的距离，确保在图内
    final labels = [
      {'text': 'LT', 'angle': -90, 'fullname': 'Logical Thinking'},
      // 逻辑思维 - 顶部
      {
        'text': 'IT/CR',
        'angle': -45,
        'fullname': 'Innovative Thinking / Creativity'
      },
      // 创新思维 - 右上
      {'text': 'CE', 'angle': 0, 'fullname': 'Communication and Expression'},
      // 沟通表达 - 右侧
      {'text': 'TC', 'angle': 45, 'fullname': 'Teamwork and Collaboration'},
      // 团队协作 - 右下
      {'text': 'LA', 'angle': 90, 'fullname': 'Learning and Adaptability'},
      // 学习适应 - 底部
      {'text': 'EM', 'angle': 135, 'fullname': 'Emotional Management'},
      // 情绪管理 - 左下
      {'text': 'DMJ', 'angle': 180, 'fullname': 'Decision-Making and Judgment'},
      // 决策判断 - 左侧
      {'text': 'EA', 'angle': 225, 'fullname': 'Execution Ability'},
      // 执行能力 - 左上
    ];

    return SizedBox(
      width: 260.w, // 增加容器大小确保标签不被裁剪
      height: 260.w,
      child: Stack(
        alignment: Alignment.center,
        clipBehavior: Clip.none,
        children: labels.map((label) {
          final int angle = label['angle'] as int;
          final double angleInRadians = angle * (math.pi / 180);
          final double x = math.cos(angleInRadians) * radius;
          final double y = math.sin(angleInRadians) * radius;

          // 更精确的标签尺寸
          double labelWidth = 50.w;
          double labelHeight = 24.w;

          // 基本偏移量计算
          double offsetX = -labelWidth / 2;
          double offsetY = -labelHeight / 2;

          // 根据设计图调整各方向标签的位置
          switch (angle) {
            case -90: // 顶部
              offsetY = -labelHeight;
              break;
            case 90: // 底部
              offsetY = 0;
              break;
            case 0: // 右侧
              offsetX = 0;
              break;
            case 180: // 左侧
              offsetX = -labelWidth;
              break;
            case -45: // 右上
              offsetX = -labelWidth * 0.2;
              offsetY = -labelHeight * 0.8;
              break;
            case 45: // 右下
              offsetX = -labelWidth * 0.2;
              offsetY = -labelHeight * 0.2;
              break;

            case 135: // 左下
              offsetX = -labelWidth * 0.8;
              offsetY = -labelHeight * 0.2;
              break;
            case 225: // 左上
              offsetX = -labelWidth * 0.8;
              offsetY = -labelHeight * 0.8;
              break;
          }

          return Positioned(
            left: 130.w + x + offsetX, // 根据容器大小调整中心点
            top: 130.w + y + offsetY,
            child: Container(
              width: labelWidth,
              height: labelHeight,
              alignment: Alignment.center,
              child: Text(
                label['text']! as String,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 12.sp,
                  color: AppColor.color7F909E,
                  fontWeight: FontWeight.w500,
                  height: 1.2,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  // 构建数据点
  Widget _buildDataPoints() {
    // 使用与分数列表一致的数据
    final dataValues = [
      0.85, // LT - Logical Thinking
      0.96, // IT/CR - Innovative Thinking / Creativity
      0.82, // CE - Communication and Expression
      0.79, // TC - Teamwork and Collaboration
      0.88, // LA - Learning and Adaptability
      0.94, // EM - Emotional Management
      0.80, // DMJ - Decision-Making and Judgment
      0.92, // EA - Execution Ability
    ];

    // 使用与标签顺序一致的颜色
    final colors = [
      Color(0xFF8A65E5), // 紫色 - 逻辑思维
      Color(0xFFCAAA66), // 金色 - 创新思维
      Color(0xFF8DC226), // 绿色 - 沟通表达
      Color(0xFF538CE6), // 蓝色 - 团队协作
      Color(0xFF00C3FF), // 浅蓝 - 学习适应
      Color(0xFFF452F4), // 粉色 - 情绪管理
      Color(0xFF13B2A3), // 青色 - 决策判断
      Color(0xFFF46681), // 红色 - 执行能力
    ];

    return SizedBox(
      width: 220.w,
      height: 220.w,
      child: Stack(
        children: List.generate(dataValues.length, (i) {
          final double angleInDegrees = i * (360 / dataValues.length) - 90;
          final double angleInRadians = angleInDegrees * (math.pi / 180);
          final double value = dataValues[i];

          // 使用图表半径计算点的位置
          final double chartRadius = 110.w;
          final double distance = value * chartRadius;

          final double x = math.cos(angleInRadians) * distance;
          final double y = math.sin(angleInRadians) * distance;

          // 计算点的中心位置
          final double centerX = chartRadius;
          final double centerY = chartRadius;

          // 点大小的一半，用于居中定位
          final double pointRadius = 4.w;

          return Positioned(
            left: centerX + x - pointRadius,
            top: centerY + y - pointRadius,
            child: Container(
              width: pointRadius * 2,
              height: pointRadius * 2,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
                border: Border.all(
                  color: colors[i],
                  width: 1.5.w,
                ),
              ),
            ),
          );
        }),
      ),
    );
  }

  // 构建分数列表
  Widget _buildScoresList() {
    // 使用与标签一致的顺序和完整名称
    final List<Map<String, dynamic>> scores = [
      {
        'name': 'Logical Thinking',
        'score': '85%',
        'color': Color(0xFF8A65E5),
      },
      {
        'name': 'Innovative Thinking / Creativity',
        'score': '96%',
        'color': Color(0xFFCAAA66),
      },
      {
        'name': 'Communication and Expression',
        'score': '82%',
        'color': Color(0xFF8DC226),
      },
      {
        'name': 'Teamwork and Collaboration',
        'score': '79%',
        'color': Color(0xFF538CE6),
      },
      {
        'name': 'Learning and Adaptability',
        'score': '88%',
        'color': Color(0xFF00C3FF),
      },
      {
        'name': 'Emotional Management',
        'score': '94%',
        'color': Color(0xFFF452F4),
      },
      {
        'name': 'Decision-Making and Judgment',
        'score': '80%',
        'color': Color(0xFF13B2A3),
      },
      {
        'name': 'Execution Ability',
        'score': '92%',
        'color': Color(0xFFF46681),
      },
    ];

    return Column(
      children: scores
          .map((item) => _buildScoreItem(
                name: item['name'],
                score: item['score'],
                color: item['color'],
              ))
          .toList(),
    );
  }

  // 构建单个分数项
  Widget _buildScoreItem({
    required String name,
    required String score,
    required Color color,
  }) {
    return Padding(
      padding: EdgeInsets.only(bottom: 12.w),
      child: Row(
        children: [
          // 颜色标记
          Container(
            width: 14.w,
            height: 8.w,
            decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.circular(20.w),
            ),
          ),

          SizedBox(width: 12.w),

          // 分数
          Text(
            score,
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: AppColor.color0C0A09,
              letterSpacing: -0.32,
              height: 1.2,
            ),
          ),

          SizedBox(width: 12.w),

          // 能力名称
          Expanded(
            child: Text(
              name,
              style: TextStyle(
                fontSize: 14.sp,
                color: AppColor.color7F909E,
                height: 1.2,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// 雷达图网格绘制器
class RadarGridPainter extends CustomPainter {
  final int sides;
  final Color color;
  final double strokeWidth;

  RadarGridPainter({
    required this.sides,
    required this.color,
    this.strokeWidth = 1.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth;

    final Path path = _createPolygonPath(size);
    canvas.drawPath(path, paint);
  }

  Path _createPolygonPath(Size size) {
    final path = Path();
    final centerX = size.width / 2;
    final centerY = size.height / 2;
    final radius = size.width / 2;

    // 创建多边形路径
    for (int i = 0; i < sides; i++) {
      final angle = (i * (360 / sides) - 90) * (math.pi / 180); // 从上方开始
      final x = centerX + radius * math.cos(angle);
      final y = centerY + radius * math.sin(angle);

      if (i == 0) {
        path.moveTo(x, y);
      } else {
        path.lineTo(x, y);
      }
    }

    path.close();
    return path;
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    if (oldDelegate is RadarGridPainter) {
      return oldDelegate.sides != sides ||
          oldDelegate.color != color ||
          oldDelegate.strokeWidth != strokeWidth;
    }
    return true;
  }
}

// 雷达图轴线绘制器
class RadarAxisPainter extends CustomPainter {
  final int sides;
  final Color color;
  final double strokeWidth;

  RadarAxisPainter({
    required this.sides,
    required this.color,
    this.strokeWidth = 1.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth;

    final centerX = size.width / 2;
    final centerY = size.height / 2;
    final radius = size.width / 2;
    
    // 最内层多边形的半径（与_buildRadarBackgroundGrid中最内层的尺寸保持一致）
    final innerRadius = 22.w; // 最内层八边形的半径（44.w的一半）

    // 绘制从内层多边形边缘到各顶点的轴线，而不是从中心点开始
    for (int i = 0; i < sides; i++) {
      final angle = (i * (360 / sides) - 90) * (math.pi / 180); // 从上方开始
      
      // 计算内层多边形边缘上的点
      final innerX = centerX + innerRadius * math.cos(angle);
      final innerY = centerY + innerRadius * math.sin(angle);
      
      // 计算外边缘点
      final outerX = centerX + radius * math.cos(angle);
      final outerY = centerY + radius * math.sin(angle);

      // 从内层多边形边缘到外边缘绘制线条
      canvas.drawLine(
        Offset(innerX, innerY),
        Offset(outerX, outerY),
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    if (oldDelegate is RadarAxisPainter) {
      return oldDelegate.sides != sides ||
          oldDelegate.color != color ||
          oldDelegate.strokeWidth != strokeWidth;
    }
    return true;
  }
}

// 雷达图数据绘制器
class RadarDataPainter extends CustomPainter {
  final List<double> dataPoints;
  final int sides;
  final Color fillColor;
  final Color strokeColor;
  final double strokeWidth;

  RadarDataPainter({
    required this.dataPoints,
    required this.sides,
    required this.fillColor,
    required this.strokeColor,
    this.strokeWidth = 1.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (dataPoints.length != sides) return; // 确保数据点数量和边数一致

    final centerX = size.width / 2;
    final centerY = size.height / 2;
    final radius = size.width / 2;

    // 绘制填充
    final Path fillPath = Path();
    for (int i = 0; i < sides; i++) {
      final double value = dataPoints[i].clamp(0.0, 1.0); // 确保值在0-1之间
      final double angle = (i * (360 / sides) - 90) * (math.pi / 180); // 从上方开始
      final double r = radius * value;
      final double x = centerX + r * math.cos(angle);
      final double y = centerY + r * math.sin(angle);

      if (i == 0) {
        fillPath.moveTo(x, y);
      } else {
        fillPath.lineTo(x, y);
      }
    }
    fillPath.close();

    final Paint fillPaint = Paint()
      ..color = fillColor
      ..style = PaintingStyle.fill;

    canvas.drawPath(fillPath, fillPaint);

    // 绘制边框
    final Paint strokePaint = Paint()
      ..color = strokeColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth;

    canvas.drawPath(fillPath, strokePaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    if (oldDelegate is RadarDataPainter) {
      return oldDelegate.dataPoints != dataPoints ||
          oldDelegate.sides != sides ||
          oldDelegate.fillColor != fillColor ||
          oldDelegate.strokeColor != strokeColor ||
          oldDelegate.strokeWidth != strokeWidth;
    }
    return true;
  }
}
